<template>
	<div class="page-evaluation-higher evaluation" :style="{backgroundImage:'url('+require('@images/evaluation-bg.png')+')'}">
		<div class="content">
            <h2 class="tc mb30 pt30"><a href="javascript:;" class="active">{{currentOptions.title}}</a></h2>
            <h3>患者信息</h3>
			<Form :model="customer" :rules="rules" :label-width="80" label-position="right">
				<Row :gutter="40" class="row">
					<Col :span="8">
						<FormItem class="plain" label="姓名" prop="customerId" >
                            <Dropdown trigger="click" style="width:100%;">
                                <Input @on-change="customerNameChange" type="text" :value="customer.customerName" :maxlength="8" placeholder="请输入患者姓名" />
                                <DropdownMenu  slot="list">
                                    <DropdownItem v-show="customerList.length" v-for="(item,i) in customerList" :key="i" ><div @click="customerGet(item.id)">{{item.customerName}}</div></DropdownItem>
                                    <DropdownItem v-show="customerList.length===0 && !searchLoading">没有结果</DropdownItem>
                                    <DropdownItem v-show="searchLoading"><Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon></DropdownItem>
                                </DropdownMenu>
                            </Dropdown>
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem class="plain" label="性别" prop="sex" >
							<RadioGroup  class="sex" :value="customer.sex">
								<Radio disabled :label="1">男</Radio>
								<Radio disabled :label="2">女</Radio>
							</RadioGroup>
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem z class="plain" label="出生日期" prop="birthday" >
							<DatePicker
                                style="width:100%;"
                                disabled
								@on-change="t=>customer.birthday=t"
								type="date"
								:value="customer.birthday"
								placeholder
							/>
						</FormItem>
					</Col>
				</Row>
                <Row :gutter="40"  class="row">
					<Col :span="8">
						<FormItem class="plain" label="手机号码" prop="mobile" >
                            <Input disabled type="tel" :value="customer.mobile" :maxlength="11" placeholder />
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem class="plain" label="患者类型" prop="customerType" >
							<Select disabled placeholder :value="customer.customerType">
								<Option
									v-for="item in diseaseTypeList"
									:value="String(item.itemKey)"
									:key="item.id"
								>{{ item.itemValue }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem class="plain" label="确诊年份" prop="careTime" >
							<DatePicker style="width:100%;" disabled :value="customer.careTime" type="datetime" placeholder />
						</FormItem>
					</Col>
					
				</Row>
                <Row :gutter="40"  class="row">
					<Col :span="8">
						<FormItem class="plain" label="身高(cm)" prop="height" >
							<Input disabled :value="customer.height" placeholder />
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem class="plain" label="体重(kg)" prop="weight" >
							<Input disabled :value="customer.weight" type="text" :maxlength="5" placeholder />
						</FormItem>
					</Col>
					<Col :span="8">
						<FormItem class="plain" label="BMI" prop="bmi" >
							<Input disabled :value="customer.bmi" type="text" :maxlength="5" placeholder />
						</FormItem>
					</Col>
				</Row>
                
			</Form>
            <h3>风险评估</h3>
            <div v-if="getLoading"><Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>题目加载中...</div>
            <Form :model="userOptions" :rules="questionRules" label-position="top">
                <div v-for="(item,i) in quesOptions" :key="i">
                    <FormItem class="plain" prop="">
                        <template slot="label">
                            <h4>
                                <span style="color:red;">*</span>
                                <span>{{(1+i) + '、'+item.questionContent}}</span>
                            </h4>
                        </template>
                        <RadioGroup @on-change="questionChange(item,i)" class="sex" v-model="userOptions[i]['value']">
                            <div class="option" v-for="(o,j) in item.options" :key="j"><Radio :label="o.optionCode">{{o.optionContent}}</Radio></div>
                        </RadioGroup>
                    </FormItem>
                </div>
            </Form>
            <Divider />
            <div class="pb30">
                <Button type="success" :loading="saveLoading" @click="evaluationSave">完成</Button>
                <Button class="ml20" type="primary" ghost @click="resetUserOptions">重填</Button>
            </div>
		</div>
	</div>
</template>
<script>

import { customerPageQueryList ,customerGet, customerQueryListByName} from '@api/customer.js'
import { evaluationGetQuestion, evaluationSave, evaluationGetResult, evaluationPageQueryList } from '@api/evaluation.js'
import { mapState } from '@lib/x_.js'
export default {
	data() {
		return {
            currentOptions: {

            },
            options: [
                {
                    title:'三高风险评估',
                    code:'SGPC',
                },
                {
                    title:'慢阻肺病风险评估',
                    code:'MXZSXFBCP',
                },
                
                {
                    title:'痛风风险评估',
                    code:'TFPC',
                },
                {
                    title:'高血压风险评估',
                    code:'GXYPC',
                },
                {
                    title:'高血脂风险评估',
                    code:'GXZPC',
                },
                {
                    title:'糖尿病健康评估',
                    code:'TNBPC',
                },
            ],
            getCustomerLoading: false,
            saveLoading: false,
            getLoading: false,
            customerList: [],
			customer: {
                customerName: '',
				customerId: '',
				sex: '',
				birthday: '',
				mobile: '',
				customerType: '',
				height: '',
				weight: '',
				bmi: ''
			},
			rules: {
                // customerId: [{required: true,type:'string', message: '请选择测评患者', trigger: 'blur' }],
            },

            questionRules: {},
            userOptions: [],
            quesOptions: [],
            quesBankId: '',
            searchLoading: false,
		}
	},
	mounted() {
        this.init()
	},
	computed: {
		...mapState(['diseaseTypeList', 'familyList', 'diseaseHistoryList', 'familyHistoryList', 'nowTreatmentList', 'tagList', 'userList'])
	},
	methods: {
        resetCustomer() {
            this.customer = {
                customerName: '',
				customerId: '',
				sex: '',
				birthday: '',
				mobile: '',
				customerType: '',
				height: '',
				weight: '',
				bmi: ''
            };
            
        },
        resetUserOptions() {
            const userOptions = this.userOptions;
            userOptions.map((item,i) => item.value = '');
            this.userOptions = userOptions;
        },
        async customerNameChange(e) {
            const keyWord = e.target.value || '';
            if (keyWord.length < 2) {
                return;
            }
            this.resetCustomer()
            this.searchLoading = true;
            customerQueryListByName({customerName:keyWord}).then(res => {
                if (res.code === "0") {
                    this.customerList = res.data;
                }
                this.searchLoading = false;
            }).catch(err => {
                this.searchLoading = false;
            })
            // customerPageQueryList({customerName:keyWord})
			// 	.then(res => {
			// 		this.searchLoading = false
			// 		if (res.code === '0') {
            //             this.customerList = res.data.items;
			// 		} else {
            //             this.$Modal.warning({
			// 				title: '查询列表',
			// 				content: res.errMsg
			// 		    })
            //         }
			// 	})
			// 	.catch(err => {
			// 		this.searchLoading = false
			// 	})
        },
        init() {
            const  { id } = this.$route.query;
            let { code } = this.$route.params;
            if (code === "GXZPC") { //高血脂改为3高
                code = "SGPC"
            }
            this.code = code;
            
            const currentOptionsIndex = this.options.findIndex((item,i) => item.code === code)
            this.currentOptions = this.options[currentOptionsIndex]
            if (id) {
                // this.customerChange(id)
                this.customerGet(id)
                // this.customerPageQueryList()
            }
            this.evaluationGetQuestion()
        },
        questionChange(obj,i){
            const optionCodes = obj.options.map((item,i) => item.optionCode)
            this.userOptions[i]['optionCodes'] = optionCodes;
            this.userOptions[i]['questionCode'] = obj.questionCode;
            this.userOptions = [...this.userOptions]
        },
        customerChange(id){
            if (this.getCustomerLoading) return;
            this.customerGet(id)
        },
        async customerGet(id){
            this.getCustomerLoading = true;
            const res = await customerGet({id})
            if (res.code === '0') {
                const { data } = res;
                const { birthday ,sex, mobile, customerType , customerInfo, customerHealth, customerName} = data;
                const { height, weight, careTime } = customerInfo
                var bmi = 0;
                if (height && weight && ( weight !==0)) {
                    try {
                        bmi = Math.floor(Number(weight) /(Number(height) * Number(height)) * 10000);
                    } catch (error) {
                        
                    }
                }
                const customer = {customerId: String(id), careTime, birthday, sex, mobile, height, weight, customerType, customerName, bmi,};
                this.customer = customer;
            }
            this.getCustomerLoading = false;
        },
        customerPageQueryList() {
			customerPageQueryList({page:1,pageSize:500 })
				.then(res => {
					this.loading = false
					if (res.code === '0') {
                        this.customerList = res.data.items;
					} else {
                        this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					    })
                    }
				})
				.catch(err => {
					this.loading = false
				})
		},
        modal(res,title){
            if (res.code === "0") {
                this.$Modal.success({
                    title: title,
                    content: res.data || '评估成功'
                })
            } else {
                this.$Modal.warning({
                    title: title,
                    content: res.errMsg || '评估出错'
                })
            }
        },
        
        evaluationSave(){
            const { customerId, } = this.customer;
            const { userOptions,quesBankId,code } = this;
            const idx = userOptions.findIndex((item,i) => !item.value)
            if (!customerId) {
                return this.$Message.warning(`请选择测评患者`)
            }
            if (idx> -1) {
                return this.$Message.warning(`请选择第 ${1+ idx}道题目的结果`)
            }
            this.saveLoading = true;
            evaluationSave({code,customerId,userOptions,quesBankId}).then(res => {
                if (res.code === "0") {
                    this.resetCustomer()
                    this.resetUserOptions()
                }
                
                this.saveLoading = false;
                this.modal(res,'风险评估')
            }).catch(err => this.saveLoading = false)
        },
		evaluationGetQuestion() {
            this.getLoading = true;
			evaluationGetQuestion({ customerId: 16, code: this.currentOptions.code }).then(res => {
                this.getLoading = false;
				if (res.code === '0') {
                    const { quesOptions , quesBankId} = res.data;
                    this.quesOptions = quesOptions;
                    console.log("quesOptions~~",quesOptions)
                    const userOptions = []
                    const questionRules = {}
                    quesOptions.map((item,i) => {

                        // optionCodes: [], questionCode: "", value: ""
                        userOptions[i] = {
                            questionCode:'', //问题编号
                            optionCodes:[],  //用户选择的选项集合
                            value:'',        //非选项值，例如：时间轴数据
                        }
                        // questionRules[i] = [{required: true,type:'string', message: '请选择测评患者', trigger: 'change' }];
                    })
                    // this.questionRules = questionRules

                    this.userOptions = userOptions;
                    this.quesBankId = quesBankId;
				}
				console.log('res--> ', res)
			}).catch(err => this.getLoading = false)
		}
    },
    watch: {
        $route() {
            this.init()
        }
    }
}
</script>
<style lang="scss" scoped>
    .row{
        margin-bottom: 10px;
    }
    h2{
        a{
            font-size: 24px;
        }
    }
    h3{
        line-height: 50px;
        font-size: 16px;
        color: #111;
    }
    h4{
        font-size: 16px;
        margin-top: 30px;
    }
    .content{
        width: 940px;
        padding-left: 30px;
        padding-right: 30px;
        margin-left: auto;
        margin-right: auto;
        max-width: 1000px;
        background-color: #fff;
    }
    .option{
        margin-left: 25px;
        .ivu-radio-wrapper{
            font-size: 14px;
        }
    }
</style>